package wetalk.software.bupt.com.wetalk.view.activity;

import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.jyt.message.Message;
import com.jyt.util.MySerializable;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import wetalk.software.bupt.com.wetalk.R;
import wetalk.software.bupt.com.wetalk.application.UserManager;
import wetalk.software.bupt.com.wetalk.communicate.AndroidClientService;
import wetalk.software.bupt.com.wetalk.listener.PushListener;
import wetalk.software.bupt.com.wetalk.model.po.ChatUser;
import wetalk.software.bupt.com.wetalk.model.po.User;
import wetalk.software.bupt.com.wetalk.util.ActivityCollector;
import wetalk.software.bupt.com.wetalk.util.SharePreferenceUtil;
import wetalk.software.bupt.com.wetalk.util.WeTalkConfig;
import wetalk.software.bupt.com.wetalk.view.dialog.CustomDialog;
import wetalk.software.bupt.com.wetalk.widget.ClearEditText;

import static android.content.ContentValues.TAG;
import static wetalk.software.bupt.com.wetalk.application.MyApplication.getContext;

public class ChangePasswordActivity extends BaseActivity {
    private RelativeLayout rvImgBack,rvImgRight;//返回和确定布局的点击
    private ClearEditText originalPassword,newPassword,checkPasswore;//原始密码，新密码，检验新密码
    private TextView txtMiddle;
    private static ChatUser saveUserInfo;
    private IntentFilter intentFilter;
    private AndroidClientService.SendBinder sendBinder;
    private PasswordUserInfoReceiver userInfoReceiver;
    private CustomDialog customDialog;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_change_password);
        saveUserInfo = UserManager.getInstance(this).getCurrentUser();
        initWidget();
        initModifyUserInfoBC();
        initEvent();

    }


    /*
    * 初始化控件
    */
    private void initWidget(){
        rvImgBack=(RelativeLayout)findViewById(R.id.rv_img_back);
        txtMiddle=(TextView)findViewById(R.id.txt_title);
        rvImgRight=(RelativeLayout)findViewById(R.id.rv_img_right);
        originalPassword =(ClearEditText) findViewById(R.id.et_original_password);
        newPassword=(ClearEditText) findViewById(R.id.et_new_password);
        checkPasswore=(ClearEditText) findViewById(R.id.et_check_newPassword);

        //客户端发送消息
        Intent bindIntent = new Intent(this, AndroidClientService.class);
        this.bindService(bindIntent, connection, BIND_AUTO_CREATE);
    }

    /*
    * 时间响应*/
    private  void initEvent(){
        //点击左侧布局事件
        rvImgBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        //中间文字“修改密码”

        txtMiddle.setText("修改密码");


        //点击确定布局事件
        rvImgRight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //获取edit_text值
                String mNewPassword = newPassword.getText().toString();
                String mOriginalPassword = originalPassword.getText().toString();
                String mCheckPassword = checkPasswore.getText().toString();
                //读取原始密码
                SharePreferenceUtil sharePreferenceUtil = new SharePreferenceUtil(getContext(), "WeTalk_SP");
                String originalPs = sharePreferenceUtil.getValue("password");

                if(mOriginalPassword.equals(""))
                {
                    Toast.makeText(ChangePasswordActivity.this,"请正确输入原密码，不可为空",Toast.LENGTH_SHORT).show();
                }
                else if (!(mOriginalPassword.equals(originalPs)))
                {
                    Toast.makeText(ChangePasswordActivity.this,"输入的原始密码不正确，请重新输入",Toast.LENGTH_SHORT).show();
                }
                else if(mOriginalPassword.equals(mNewPassword)){
                    Toast.makeText(ChangePasswordActivity.this,"原密码和新密码相同，请重新输入",Toast.LENGTH_SHORT).show();
                }
                //验证新密码
                else if(!(mNewPassword.equals(mCheckPassword)))
                {
                    Toast.makeText(ChangePasswordActivity.this,"两次输入的密码不相同，请重新输入",Toast.LENGTH_SHORT).show();
                }
                else if((mNewPassword.equals(mCheckPassword))&&(mNewPassword.equals(mCheckPassword)))
                {
                    if(isPassword(mNewPassword)==false)
                        Toast.makeText(ChangePasswordActivity.this,"请输入六位数字密码",Toast.LENGTH_SHORT).show();
                    else{
                        saveUserInfo.setPassword(mNewPassword);
                        sendModifyUserInfo(mNewPassword, new PushListener() {
                            @Override
                            public void onSuccess() {
                                Toast.makeText(ChangePasswordActivity.this, "发送成功", Toast.LENGTH_SHORT).show();
                            }

                            @Override
                            public void onFailure(int var1, String var2) {
                                Toast.makeText(ChangePasswordActivity.this, "发送失败", Toast.LENGTH_SHORT).show();
                            }
                        });

                        CustomDialog.getDialog(ChangePasswordActivity.this,"正在修改...").show();
                    }


                }
            }
        });

    }

    //发送修改消息
    private void sendModifyUserInfo(String context, final PushListener pushCallback)  {
        User saveUser = UserManager.getInstance(this).getCurrentUser();
        final String targetId = "sys_userinfo";
        final String userId= saveUser.getUserID();
        final JSONObject json=new JSONObject();
        try {
            json.put("id",userId);
            json.put("phone",saveUser.getPhone());
            json.put("email",saveUser.getEmail());
            json.put("passwd",context);

        } catch (JSONException e) {
            e.printStackTrace();
        }
        Thread thread=new Thread(new Runnable() {
            @Override
            public void run() {
                byte[] bs;
                bs = MySerializable.object_bytes(json.toString());

                Message msg = new Message(userId,targetId,"modifyUserInfo",bs);
                sendBinder.sendMessage(msg);
                Log.i(TAG, "send message: "+msg);
                //pushCallback.onSuccess();
            }
        });
        thread.start();

    }

    //验证新密码，当前默认验证方式为六位数字
    private static boolean isPassword(String mobiles){
        Pattern p = Pattern.compile("^\\d{6}$");
        Matcher m = p.matcher(mobiles);
        return m.matches();
    }
    //注册广播接收器
    private void initModifyUserInfoBC(){
        //接收广播
        intentFilter=new IntentFilter(WeTalkConfig.BROADCAST_MODIFY_USER_INFO);
        userInfoReceiver=new PasswordUserInfoReceiver();
        registerReceiver(userInfoReceiver,intentFilter);
    }

    //广播接收器
    class PasswordUserInfoReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            CustomDialog.getDialog(ChangePasswordActivity.this,"正在修改...").close();
            String result = "";
            String content=intent.getStringExtra("result");
            try {
                JSONObject json=new JSONObject(content);
                result=json.getString("result");
                if(result.equals("success")){
                    Toast.makeText(context, "修改成功", Toast.LENGTH_SHORT).show();
                    SharePreferenceUtil sharePreferenceUtil = new SharePreferenceUtil(context, "WeTalk_SP");
                    User user = (User)sharePreferenceUtil.readObject("user");
                    user.setPassword(newPassword.getText().toString());
                    sharePreferenceUtil.saveObject(user,"user");
                    sharePreferenceUtil.saveValue("no","isLogin");

                    //停止service
                    Intent stop=new Intent(ChangePasswordActivity.this,AndroidClientService.class);
                    ChangePasswordActivity.this.stopService(stop);

                    ActivityCollector.finishAll();

                    Intent intent1 = new Intent(ChangePasswordActivity.this,LoginActivity.class);
                    startActivity(intent1);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }


        }
    }

    private ServiceConnection connection=new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            sendBinder= (AndroidClientService.SendBinder) iBinder;
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
        }
    };


    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(userInfoReceiver);
        unbindService(connection);
    }
}


